package com.lzjt.service.Impl;

import com.lzjt.mapper.AccountMapper;
import com.lzjt.model.AccountModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AccountModel accountModel = accountMapper.securityLogin(username);
        if (accountModel == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        String role = accountModel.getUtype();
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(role);

        // 使用Spring Security提供的User类构建UserDetails对象
        return User.builder()
                .username(accountModel.getUname())
                .password(accountModel.getPwd())
                .authorities(auths)
                .build();
    }
}
